﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model.Enum;
namespace HZ.DrugTrade.Web.Hospitals.SalesReturn
{
    public partial class ReturnGoodsOrderCheck : BasePage
    {
        public ReturnGoodsOrderCheck()
        {
            this.ModuleNo = Module.退货单管理.ToString();
        }
        bool flag = true;//控制退货单页面是否执行跳转2009-11-26
        public string ReturnPlanname = "";//采购单名称
        public string RetrunPlanID = "";//采购单ID
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HZ.DrugTrade.Web.Function.IsThreeLevel())//项目查询条件仅三级医院可见
            {
                this.ddlProjectid.Visible = false;
                this.lblProjectid.Visible = false;
            }
            ReturnPlanname = Request.QueryString["TINN"];//ReturnSerialID退货单名字
            RetrunPlanID = Request.QueryString["TIDN"];//采购单id
            if (!Page.IsPostBack)
            {
                banding();
            }
        }
        #region #原绑定
        ///// <summary>
        ///// 绑定
        ///// </summary>
        //private void banding()
        //{
        //    IBLL_Purchase IBLLP = Factory.BLL_Purchase();
        //    HZ.DrugTrade.Model.Query.ReturnMerchandiseHospital aReturnMerchandiseHospital = new HZ.DrugTrade.Model.Query.ReturnMerchandiseHospital();
        //    aReturnMerchandiseHospital.HospitalID = CurrentAccount.GetUser().Org.OrgID;
        //    //2009-11-26
        //    aReturnMerchandiseHospital.ProductName = this.txtProductName.Text;
        //    aReturnMerchandiseHospital.MedicineModelName = this.txtMedicineModel.Text;
        //    aReturnMerchandiseHospital.Outlookc = this.txtOutLookc.Text;
        //    aReturnMerchandiseHospital.CompanyName_PS = this.txtCompanyName_PS.Text;
        //    aReturnMerchandiseHospital.CompanyName_SC = txtCompanyname_sc.Text;

        //    aReturnMerchandiseHospital.NoComfirmStatus = 0;// 初始状态
        //    //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
        //    int totalCount = 0;

        //    gvwReturngoods.PageSize = AspNetPager1.PageSize;
        //    //aReturnMerchandiseHospital.Append = " ReturnCountSum<stock AND ( ProcureCatalogID+Companyid_ps NOT IN (SELECT ProcureCatalogID +companyid FROM TB_ReturnMerchandiseDetail where ReturnSerialID='" + RetrunPlanID.Replace("'", "") + "')) ";

        //    //过滤条件改为 库存大于零的产品
        //    aReturnMerchandiseHospital.Append = " Stock > '0' and ProcureCatalogID+CompanyID_PS  NOT IN (SELECT ProcureCatalogID +companyid "
        //       + "FROM TB_ReturnMerchandiseDetail where  ReturnState=0 OR ReturnSerialID='" + RetrunPlanID.Replace("'", "") + "' )";

        //    gvwReturngoods.DataSource = IBLLP.GetReturnMerchandis_Hospital(aReturnMerchandiseHospital, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
        //    gvwReturngoods.DataBind();
        //    AspNetPager1.RecordCount = totalCount;
        //}
        #endregion
        private void Setbind()
        {
            IList<HZ.DrugTrade.Model.View.Distribution> PurchaseOrderDetailList;
            IBLL_Purchase iPurchase = Factory.BLL_Purchase();
            int totalRecord = 0;
            Model.Query.Distribution qryCondition = new HZ.DrugTrade.Model.Query.Distribution();
            qryCondition.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            qryCondition.DistributeState = 1;
            qryCondition.GoodsName = txtGoodsName.Text.Trim();
            qryCondition.CompanyName_PS = txtCompanyName_PS.Text.Trim();
            qryCondition.Material = this.txtMaterial.Text;
            qryCondition.Outlookc = this.txtOutLookc.Text;
            qryCondition.CompanyName_SC = txtCompanyname_sc.Text;
            qryCondition.IsInvoice = false;
            qryCondition.SortFields = " DistributeTime desc,OrderName ASC ";
            qryCondition.Append = " Dis_WarehouseCount> 0 and  returncount = 0 ";
            PurchaseOrderDetailList = iPurchase.GetPurchaseOrderDetail_DistributeByWhere(qryCondition, this.AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalRecord);
            gvwReturngoods.DataSource = PurchaseOrderDetailList;
            gvwReturngoods.DataBind();

            AspNetPager1.RecordCount = totalRecord;
        }

        private void banding()
        {

            IBLL_Purchase IBLLP = Factory.BLL_Purchase();
            HZ.DrugTrade.Model.Query.ReturnMerchandiseHospital aReturnMerchandiseHospital = new HZ.DrugTrade.Model.Query.ReturnMerchandiseHospital();
            aReturnMerchandiseHospital.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            aReturnMerchandiseHospital.GoodsName = this.txtGoodsName.Text;
            aReturnMerchandiseHospital.PinyinCode = this.txtpinyincode.Text.Trim();
            aReturnMerchandiseHospital.Material = this.txtMaterial.Text;
            aReturnMerchandiseHospital.Outlookc = this.txtOutLookc.Text;
            aReturnMerchandiseHospital.CompanyName_PS = this.txtCompanyName_PS.Text;
            aReturnMerchandiseHospital.CompanyName_SC = txtCompanyname_sc.Text;
            //aReturnMerchandiseHospital.ProjectID = this.ddlProjectid.SelectedValue;
            if (this.ddlProjectid.Visible != false)
            {
                aReturnMerchandiseHospital.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                aReturnMerchandiseHospital.ProjectID = "0001";
            }
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalCount = 0;
            //edit by xuyi 去掉是否有企业未确认(1有未确认0无未确认 3 初始状态)
            //aReturnMerchandiseHospital.NoComfirmStatus = 0;
            //过滤条件改为 库存大于零的产品
            //aReturnMerchandiseHospital.Append = " stock>0 AND ( ProcureCatalogID||CompanyID_PS   NOT IN (SELECT ProcureCatalogID||CompanyID FROM TB_ReturnMerchandiseDetail where ReturnSerialID='" + RetrunPlanID.Replace("'", "") + "')) ";
            //edit by xuyi
            //OrderDetailID||CompanyID_PS||to_char(ProcurePrice)   NOT IN (SELECT OrderDetailID||CompanyID||to_char(cast(Orginalprice as number(18,2)))  FROM TB_ReturnMerchandiseDetail where ReturnSerialID='" + RetrunPlanID.Replace("'", "") + "') and 
            aReturnMerchandiseHospital.Append = "WarehouseCount>0 and orderdetailid NOT IN(SELECT orderdetailid FROM TB_ReturnMerchandiseDetail  where returnstate=0) and  OrderDetailID NOT IN(SELECT OrderDetailID FROM Tb_Distribution where isinvoice=1) ";
            aReturnMerchandiseHospital.SortFields = "ProcureCatalogID";

            //gvwReturngoods.PageSize = AspNetPager1.PageSize;
            gvwReturngoods.DataSource = IBLLP.GetReturnMerchandis_Hospital(aReturnMerchandiseHospital, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);

            gvwReturngoods.DataBind();

            AspNetPager1.RecordCount = totalCount;

        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            banding();
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            banding();
        }

        protected void lbnSwitch_Click(object sender, EventArgs e)
        {
            if (lbnSwitch.CommandArgument == "simple")
            {
                ltlAdvance.Text = "";
                lbnSwitch.CommandArgument = "advance";
                lbnSwitch.Text = "简单查询";
            }
            else
            {
                ltlAdvance.Text = "<tbody id='advance' style='display:none'>";
                lbnSwitch.CommandArgument = "simple";
                lbnSwitch.Text = "高级查询";

                //清空数据
                //txtAccountFrom.Text = "";
                //txtAccountTo.Text = "";
                //txtEndTimeFrom.Text = "";
                //txtEndTimeTo.Text = "";
                //txtPlanTimeFrom.Text = "";
                //txtPlanTimeTo.Text = "";
                //txtStartTimeFrom.Text = "";
                //txtStartTimeTo.Text = "";
            }
        }
        /// <summary>
        /// 加入退货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            IBLL_Purchase IBLLP = Factory.BLL_Purchase();

            string nOrgID = CurrentAccount.GetUser().Org.OrgID;//医疗机构ID

            List<HZ.DrugTrade.Model.ReturnMerchandiseDetail> DistributionBatchRecordList = new List<HZ.DrugTrade.Model.ReturnMerchandiseDetail>();
            for (int i = 0; i < this.gvwReturngoods.Rows.Count; i++)
            {
                if (gvwReturngoods.Rows[i].RowType == DataControlRowType.DataRow)
                {
                    System.Web.UI.HtmlControls.HtmlInputCheckBox chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)gvwReturngoods.Rows[i].FindControl("checkbox1");
                    if (chk.Checked == true)
                    {

                        //申明两个实体，存放配送的信息
                        HZ.DrugTrade.Model.ReturnMerchandiseDetail aReturnMerchandise = new HZ.DrugTrade.Model.ReturnMerchandiseDetail();

                        //获得退货量
                        TextBox txtReturnnum = (TextBox)gvwReturngoods.Rows[i].FindControl("txtCount");
                        int? iReturnnum = new HZ.Common.ConvertHelper(txtReturnnum.Text.Trim()).ToInt32;

                        //该次入库量
                        int? nGwvStock = Convert.ToInt32(((Label)gvwReturngoods.Rows[i].FindControl("lblStock")).Text.Trim());

                        //获得采购价格
                        TextBox tPrice = (TextBox)gvwReturngoods.Rows[i].FindControl("txtPrice");

                        decimal? price = new HZ.Common.ConvertHelper(tPrice.Text.Trim()).ToDecimal;

                        string procurecataLogID = new HZ.Common.ConvertHelper(gvwReturngoods.DataKeys[i].Values["ProcureCatalogID"].ToString()).String;
                        string orderDetailID = new HZ.Common.ConvertHelper(gvwReturngoods.DataKeys[i].Values["OrderDetailID"].ToString()).String;
                        bool flag2 = HZ.DrugTrade.BLLFactory.Factory.BLL_Purchase().IsReturnning(orderDetailID, price, nOrgID);
                        if (flag2)//如果已在退货流程中
                        {
                            HZ.Web.WebUtil.Alert("该订单已在退货流程中！", this);
                            return;
                        }
                        bool flag1 = HZ.DrugTrade.BLLFactory.Factory.BLL_Purchase().IsInvoiced(orderDetailID);
                        if (flag1)//如果已在退货流程中
                        {
                            HZ.Web.WebUtil.Alert("该订单发票已开不能退货！", this);
                            return;
                        }
                        //退货理由 
                        TextBox txtReason = (TextBox)gvwReturngoods.Rows[i].FindControl("txtReason");

                        string Reason = txtReason.Text.Trim();
                        if (iReturnnum <= 0 || iReturnnum == null)
                        {
                            HZ.Web.WebUtil.Alert("请填写退货数量！", this);
                            ((TextBox)gvwReturngoods.Rows[i].FindControl("txtCount")).Focus();
                            flag = false;
                            return;

                        }
                        //  else if (iReturnnum + nReturnCountSum > nGwvStock)//iReturnnum表示填写的退货数量，nReturnCountSum表示以退货数量。
                        else if (iReturnnum > nGwvStock)//iReturnnum表示填写的退货数量，nGwyStock当前库存
                        {
                            HZ.Web.WebUtil.Alert("退货数量大于剩余入库数量，请重新填写！", this);
                            ((TextBox)gvwReturngoods.Rows[i].FindControl("txtCount")).Focus();
                            flag = false;
                            return;
                        }
                        else if (string.IsNullOrEmpty(Reason))
                        {
                            HZ.Web.WebUtil.Alert("请填写退货理由！", this);
                            ((TextBox)gvwReturngoods.Rows[i].FindControl("txtReason")).Focus();
                            flag = false;
                            return;
                        }
                        else
                        {

                            //获得采购价格
                            TextBox txtPrice = (TextBox)gvwReturngoods.Rows[i].FindControl("txtPrice");

                            decimal? iPrice = new HZ.Common.ConvertHelper(txtPrice.Text.Trim()).ToDecimal;
                            //if (iPrice == null || iPrice <= 0)
                            //{
                            //    HZ.Web.WebUtil.Alert("请填写采购价格！", this);
                            //    ((TextBox)gvwReturngoods.Rows[i].FindControl("txtPrice")).Focus();
                            //    return;
                            //}

                            aReturnMerchandise.RetrunPrice = iPrice;
                            aReturnMerchandise.orginalPrice = iPrice;
                            //采购单明细ID
                            string strProcureCatalogID = new HZ.Common.ConvertHelper(gvwReturngoods.DataKeys[i].Values["ProcureCatalogID"].ToString()).String;
                            string strorderDetailID = new HZ.Common.ConvertHelper(gvwReturngoods.DataKeys[i].Values["OrderDetailID"].ToString()).String;
                            string strBatchrecordID = new HZ.Common.ConvertHelper(gvwReturngoods.DataKeys[i].Values["BatchrecordID"].ToString()).String;
                            aReturnMerchandise.ProcureCatalogID = strProcureCatalogID;
                            aReturnMerchandise.BatchRecordID = strBatchrecordID;
                            aReturnMerchandise.OrderDetailID = strorderDetailID;
                            aReturnMerchandise.ReturnCount = iReturnnum;
                            aReturnMerchandise.ReturnSerialDetailID = Guid.NewGuid().ToString();
                            // aReturnMerchandise.RetrunPrice = Convert.ToDecimal(((Label)gvwReturngoods.Rows[i].FindControl("lblPrice")).Text.Trim());
                            aReturnMerchandise.CompanyID = new HZ.Common.ConvertHelper(gvwReturngoods.DataKeys[i].Values["CompanyID_PS"].ToString()).String;
                            aReturnMerchandise.ReturnSerialID = Request.QueryString["TIDN"];//ReturnSerialID退货单ID
                            aReturnMerchandise.Reason = Reason;
                            DistributionBatchRecordList.Add(aReturnMerchandise);
                        }
                    }
                }

            }
            if (DistributionBatchRecordList.Count > 0)
            {
                IBLL_Purchase I_Purchase = Factory.BLL_Purchase();
                HZ.DrugTrade.Model.ReturnMerchandise reteruMer = new HZ.DrugTrade.Model.ReturnMerchandise();
                reteruMer.ReturnSerialID = Request.QueryString["TIDN"];//ReturnSerialID退货单ID
                int nSuccess = I_Purchase.AddReturnMerchandiseDetail_Batch(reteruMer, DistributionBatchRecordList);
                if (nSuccess == 1)
                {
                    HZ.Web.WebUtil.Alert("保存成功", this);
                    banding();
                    //HZ.Web.WebUtil.RedirectByScript("RetrunGoodsOderUpdate.aspx?TIDN=" + Request.QueryString["TIDN"] + "&TINN=" + HttpUtility.UrlEncode(Request.QueryString["TINN"]));
                }
                else if (nSuccess == 0)
                {
                    HZ.Web.WebUtil.Alert("保存失败", this);
                    banding();
                }
            }
        }


        /// <summary>
        /// 完成退货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFinish_Click1(object sender, EventArgs e)
        {
            btnAdd_Click(null, null);
            if (flag)
            {
                HZ.Web.WebUtil.RedirectByScript("RetrunGoodsOderUpdate.aspx?TIDN=" + Request.QueryString["TIDN"] + "&TINN=" + HttpUtility.UrlEncode(Request.QueryString["TINN"]));
            }
            //Response.Redirect("RetrunGoodsOderUpdate.aspx?TIDN=" + Request.QueryString["TIDN"] + "&TINN=" + HttpUtility.UrlEncode(Request.QueryString["TINN"]));

        }
        /// <summary>
        /// 导出2009-11-26
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExport_Click(object sender, EventArgs e)
        {

            IBLL_Purchase IBLLP = Factory.BLL_Purchase();
            HZ.DrugTrade.Model.Query.ReturnMerchandiseHospital aReturnMerchandiseHospital = new HZ.DrugTrade.Model.Query.ReturnMerchandiseHospital();
            aReturnMerchandiseHospital.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            aReturnMerchandiseHospital.GoodsName = this.txtGoodsName.Text;
            //aReturnMerchandiseHospital.ProjectID = this.ddlProjectid.SelectedValue;
            if (this.ddlProjectid.Visible != false)
            {
                aReturnMerchandiseHospital.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                aReturnMerchandiseHospital.ProjectID = "0001";
            }
            aReturnMerchandiseHospital.Material = this.txtMaterial.Text;
            aReturnMerchandiseHospital.PinyinCode = this.txtpinyincode.Text.Trim();
            aReturnMerchandiseHospital.Outlookc = this.txtOutLookc.Text;
            aReturnMerchandiseHospital.CompanyName_PS = this.txtCompanyName_PS.Text;
            aReturnMerchandiseHospital.CompanyName_SC = txtCompanyname_sc.Text;
            int totalCount = 0;
            aReturnMerchandiseHospital.Append = "WarehouseCount>0 and orderdetailid NOT IN(SELECT orderdetailid FROM TB_ReturnMerchandiseDetail  where returnstate=0) and  OrderDetailID NOT IN(SELECT OrderDetailID FROM Tb_Distribution where isinvoice=1) ";
            aReturnMerchandiseHospital.SortFields = "ProcureCatalogID";
            IList<Model.View.ReturnMerchandiseHospital> ReturnMerchandiseHospitalList = IBLLP.GetReturnMerchandis_Hospital(aReturnMerchandiseHospital, 1, 0, out totalCount);
            System.Data.DataTable dt = HZ.Data.ModelConvert.GetDataTableFromModel(ReturnMerchandiseHospitalList);
            HZ.Excel.ExcelHelper.ExportDataForWeb(dt, gvwReturngoods);
        }
    }
}
